<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

const ruleFormRef = ref<FormInstance>()

// 校验第二次输入的新密码
const checkRePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        return callback(new Error('请再次输入密码'))
    }
    if (value !== ruleForm.newPass) {
        return callback(new Error('两次输入密码不一致'))
    } else {
        callback()
    }
}

// 校验新输入的密码
const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入新的密码'))
    } else if (value == ruleForm.oldPass) {
        callback(new Error("新密码不得同旧密码一致"))
    } else {
        callback()
    }
}

const ruleForm = reactive({
    oldPass: '',
    newPass: '',
    rePass: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
    oldPass: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
    newPass: [{ validator: validatePass, trigger: 'blur' }],
    rePass: [{ validator: checkRePass, trigger: 'blur' }],
})

// 点击提交按钮, 调用后台接口
import { updatePasswordService } from '@/api/user.js'
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
        let result = null
        // 校验通过
        if (valid) {
            result = await updatePasswordService(ruleForm)
            if (result.data == '修改成功') {
                ElMessage({
                    message: '修改成功',
                    type: 'success'
                })
                resetForm(formEl)
                // 后台校验失败
            } else {
                ElMessage.error(`修改失败: ${result.data}`)
            }
        } else {
            ElMessage.error(`修改失败: 校验不通过`)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    //重置所有信息
    formEl.resetFields()
}
</script>

<template>
    <el-card style="max-width: 800px">
        <el-form ref="ruleFormRef" style="max-width: 500px" :model="ruleForm" status-icon :rules="rules"
            label-width="auto" class="demo-ruleForm">
            <el-form-item label="原密码" prop="oldPass">
                <el-input v-model="ruleForm.oldPass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPass">
                <el-input v-model="ruleForm.newPass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="确定新密码" prop="rePass">
                <el-input v-model="ruleForm.rePass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    提交
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>